<template>
	<el-switch v-model="value" :loading="loading" :active-text="options.activeText" :inactive-text="options.inactiveText"
		:active-value="options.activeValue" :inactive-value="options.inactiveValue" :active-color="options.activeColor"
		:inactive-color="options.inactiveColor" :before-change="onSwitchChange" />
</template>

<script setup>
import { ElNotification } from "element-plus"
import { computed, shallowRef } from "vue"
import { postAxios } from "/axios"

const props = defineProps({
	column: {
		type: Object,
	},
	data: {},
	index: {
		type: Number,
	},
})

const loading = shallowRef(false)
const value = computed({
	get() {
		if (props.column.key) {
			return props.data[props.column.key]
		} else {
			return ""
		}
	},
	set(value) {
		if (props.column.key) {
			props.data[props.column.key] = value
		}
	},
})
const willChangeValue = computed(() => {
	if (value.value === options.value.activeValue) {
		return options.value.inactiveValue
	} else {
		return options.value.activeValue
	}
})
const options = computed(() => {
	if (props.column.switch) {
		return {
			activeText: props.column.switch.activeText || "是",
			inactiveText: props.column.switch.inactiveText || "否",
			activeValue: props.column.switch.activeValue == undefined ? 1 : props.column.switch.activeValue,
			inactiveValue: props.column.switch.inactiveValue == undefined ? 2 : props.column.switch.inactiveValue,
			activeColor: props.column.switch.activeColor || "#13ce66",
			inactiveColor: props.column.switch.inactiveColor || "#ff4949",
			field: props.column.switch.field || "status",
		}
	}
	return {
		activeText: "是",
		inactiveText: "否",
		activeValue: 1,
		inactiveValue: 2,
		activeColor: "#13ce66",
		inactiveColor: "#ff4949",
		field: "status",
	}
})

async function onSwitchChange() {
	if (!props.data.id || !props.column.url) {
		return Promise.reject(false)
	}
	loading.value = true
	try {
		await postAxios(props.column.url, {
			id: props.data.id,
			[options.value.field]: willChangeValue.value,
		})
		loading.value = false
		ElNotification.success({
			title: "操作成功",
		})
		return Promise.resolve(true)
	} catch (error) {
		loading.value = false
		ElNotification.error({
			title: "操作失败",
			message: error,
		})
		return Promise.reject(false)
	}
}
</script>

<script>
export default {
	name: "table-column-switch",
}
</script>

<style lang="scss" scoped></style>
